/* eslint-disable @typescript-eslint/ban-types */
/*
 * @Author: 陈明烽
 * @Date: 2021-04-06 13:01:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-19 16:41:01
 * @FilePath: /evdata-hydrogen-umi/src/hooks/index.ts
 * @Description: 自定义hooks
 */
import type { RefObject } from 'react';
import { useEffect, useState, useCallback } from 'react';
import type { FormInstance } from 'antd';

type RecursivePartial<T> = T extends object
  ? {
      [P in keyof T]?: T[P] extends (infer U)[]
        ? RecursivePartial<U>[]
        : T[P] extends object
        ? RecursivePartial<T[P]>
        : T[P];
    }
  : any;

/**
 * @description: 动态的获取表单中的值
 * @param {*} T
 * @return {*}
 */
export const useFormGetFieldsValue = <T>(form: FormInstance<T>) => {
  const [formValues, setformValues] = useState<Partial<T>>();
  const onValuesChange = useCallback((v: Partial<T>, obj: T) => {
    setformValues(obj);
  }, []);
  /**useCallback 返回的是状态函数，在使用的时候可以作为依赖项，如果不使用useCallback，则不能作为依赖项 */
  const upDateFormValues = useCallback(
    (values: Partial<T>) => {
      setformValues((prev) => {
        return {
          ...prev,
          ...values,
        };
      });
      form.setFieldsValue(values as RecursivePartial<T>);
    },
    [form],
  );
  const resetForm = useCallback(()=>{
    form.resetFields();
    setformValues(undefined)
  },[form])
  return { formValues, onValuesChange, upDateFormValues,resetForm };
};
